package com.xiaoyi.common.security;

import com.xiaoyi.entity.SysUser;
import com.xiaoyi.service.SysUserService;
import com.xiaoyi.util.JwtUtils;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtException;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;

/**
 * @author 小易
 * @version 1.0
 * @description TODO JWT验证过滤器
 * @date 2022/12/6 17:13
 */
public class JwtAuthenticationFilter extends BasicAuthenticationFilter {

    @Resource
    private SysUserService userService;

    @Resource
    private MyUserDetailsServiceImpl myUserDetailsService;

    private static final String[] URL_WHITELIST = {
            "/login",
            "/logout",
            "/image/**",
//            "/test/**",
            "/captcha",
            "/password"
    };

    public JwtAuthenticationFilter(AuthenticationManager authenticationManager) {
        super(authenticationManager);
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        String token = request.getHeader("token");
        System.out.println("请求url:" + request.getRequestURI());
        //
        if (!StringUtils.hasText(token) || Arrays.asList(URL_WHITELIST).contains(request.getRequestURI())) {
            chain.doFilter(request, response);
            return;
        }
        Claims claims = JwtUtils.parseToken(token);
        if (claims == null) {
            throw new JwtException("Token不存在或已过期！");
        }

        String username = claims.get("username", String.class);

        SysUser userInfo = userService.getByUsername(username);

        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(username, null, myUserDetailsService.getUserAuthority(userInfo.getId()));
        SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
        chain.doFilter(request, response);
    }


}
